#!/usr/bin/python
# -*- coding:utf-8 -*-
# @author  : micah
# @time    :  
# @function: 使用csv保存B站视频信息
# @version :


import requests
import csv

"""
url = 'https://search.bilibili.com/video?keyword=%E7%BE%8E%E5%A5%B3&from_source=webtop_search&spm_id_from=333.1007&search_source=5'

api: "https://api.bilibili.com/x/web-interface/wbi/search/type?
    category_id=&search_type=video&ad_resource=5654&__refresh__=true
    &_extra=&context=&page=1&page_size=42&from_source=&from_spmid=333.337&platform=pc
    &highlight=1&single_column=0&keyword=jk&qv_id=BqSNWQfDyjk7D19QXjEELV4rRo9hX1GG
    &source_tag=3&gaia_vtoken=&dynamic_offset=0&web_location=1430654&w_rid=b0b386342fdc619f4e589b32b92832f0
    &wts=1705331361"
"""


class SaveVideoInfo:
    def __init__(self):
        self.url = "https://api.bilibili.com/x/web-interface/wbi/search/type?category_id=&search_type=video&ad_resource=5654&__refresh__=true&_extra=&context=&page=1&page_size=42&from_source=&from_spmid=333.337&platform=pc&highlight=1&single_column=0&keyword=jk&qv_id=BqSNWQfDyjk7D19QXjEELV4rRo9hX1GG&source_tag=3&gaia_vtoken=&dynamic_offset=0&web_location=1430654&w_rid=b0b386342fdc619f4e589b32b92832f0&wts=1705331361"

        self.headers = {
            'cookie': "i-wanna-go-back=-1; buvid4=01713F15-4A44-9808-ABCA-92058748B93150251-022050910-r9+husXb8emY1pYkQ/5/5Q%3D%3D; buvid_fp=ee0bdf6338ebc42ad157e76dea71cc36; LIVE_BUVID=AUTO9316532153826353; CURRENT_FNVAL=4048; sid=71phembi; innersign=0; buvid3=62501C2E-8F53-EA49-4993-9A3451EB59E057156infoc; b_nut=1705330957; b_ut=7; b_lsid=D69C11012_18D0DA57B2B; bsource=search_baidu; _uuid=E9B108738-10E6E-6377-8D7B-E57E1C8109AD765306infoc; enable_web_push=DISABLE; header_theme_version=undefined; home_feed_column=4; browser_resolution=1279-675; bili_ticket=eyJhbGciOiJIUzI1NiIsImtpZCI6InMwMyIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MDU1OTAzNDMsImlhdCI6MTcwNTMzMTA4MywicGx0IjotMX0.cgLTqg9IpT9Pv488tGPVFVJnpGvhTHwH-5P9N8-MfgY; bili_ticket_expires=1705590283; PVID=1",
            # 'referer': 'https://www.bilibili.com/',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'
        }

    def save(self):
        with open('video_info.csv', 'a', encoding='utf-8', newline='') as f:
            # 1.定义表头
            field_names = ['author', 'arcurl', 'tag']
            f_csv = csv.DictWriter(f, fieldnames=field_names)
            f_csv.writeheader()
            for page in range(1, 6):
                response = requests.get(self.url.format(page), headers=self.headers).json()
                for result in response['data']['result']:
                    item = dict()
                    item['author'] = result['author']
                    item['arcurl'] = result['arcurl']
                    item['tag'] = result['tag']
                    print(item)
                    f_csv.writerow(item)


svi = SaveVideoInfo()
svi.save()
